from django.test import TestCase
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient
from rest_framework import status  # 添加这行导入
from apps.chefs.models import Chef
from apps.orders.models import Order

User = get_user_model()

class ReviewTestCase(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.customer = User.objects.create_user(
            email='customer@test.com',
            password='testpass123',
            user_type='consumer'
        )
        self.chef_user = User.objects.create_user(
            email='chef@test.com',
            password='chefpass123',
            user_type='chef'
        )
        self.chef = Chef.objects.create(user=self.chef_user)
        
        self.order = Order.objects.create(
            customer=self.customer,
            chef=self.chef,
            status='completed',
            total_amount=100.00
        )

    def test_create_review(self):
        self.client.force_authenticate(user=self.customer)
        
        data = {
            'order': self.order.id,
            'food_quality': 5,
            'service': 4,
            'cleanliness': 5,
            'comment': '非常棒的体验！'
        }
        
        response = self.client.post('/api/reviews/create/', data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response.data['overall_rating'], 4.8)
        
        self.chef.refresh_from_db()
        self.assertEqual(self.chef.rating, 4.8)
        self.assertEqual(self.chef.review_count, 1)

    def test_duplicate_review(self):
        self.client.force_authenticate(user=self.customer)
        
        data = {
            'order': self.order.id,
            'food_quality': 5,
            'service': 4,
            'cleanliness': 5
        }
        
        # 第一次创建
        self.client.post('/api/reviews/create/', data)
        # 第二次创建应失败
        response = self.client.post('/api/reviews/create/', data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)